package znet

import (
	"errors"
	"fmt"
	"gitee.com/jiangjiali/z-tcp/ziface"
	"sync"
)

/*
	ConnManager 连接管理模块
*/
type ConnManager struct {
	connections map[int64]ziface.IConnection
	connLock    sync.RWMutex
}

/*
	NewConnManager 创建一个链接管理
*/
func NewConnManager() *ConnManager {
	return &ConnManager{
		connections: make(map[int64]ziface.IConnection),
	}
}

// Add 添加链接
func (connMgr *ConnManager) Add(conn ziface.IConnection) {
	connMgr.connLock.Lock()
	//将conn连接添加到ConnMananger中
	connMgr.connections[conn.GetConnID()] = conn
	connMgr.connLock.Unlock()

	fmt.Println("添加到连接管理器成功: conn数量:", connMgr.Len())
}

// Remove 删除连接
func (connMgr *ConnManager) Remove(conn ziface.IConnection) {
	connMgr.connLock.Lock()
	//删除连接信息
	delete(connMgr.connections, conn.GetConnID())
	connMgr.connLock.Unlock()

	fmt.Println("移除连接 ConnID:", conn.GetConnID(), " 成功! conn数量:", connMgr.Len())
}

// Get 利用ConnID获取链接
func (connMgr *ConnManager) Get(connID int64) (ziface.IConnection, error) {
	connMgr.connLock.RLock()
	defer connMgr.connLock.RUnlock()

	if conn, ok := connMgr.connections[connID]; ok {
		return conn, nil
	}

	return nil, errors.New("conn没有被发现")
}

// Len 获取当前连接
func (connMgr *ConnManager) Len() int {
	connMgr.connLock.RLock()
	length := len(connMgr.connections)
	connMgr.connLock.RUnlock()
	return length
}

// ClearConn 清除并停止所有连接
func (connMgr *ConnManager) ClearConn() {
	connMgr.connLock.Lock()

	for connID, conn := range connMgr.connections {
		conn.Stop()
		delete(connMgr.connections, connID)
	}
	connMgr.connLock.Unlock()

	fmt.Println("清除所有连接成功: conn数量:", connMgr.Len())
}

//ClearOneConn  利用ConnID获取一个链接 并且删除
func (connMgr *ConnManager) ClearOneConn(connID int64) {
	connMgr.connLock.Lock()
	defer connMgr.connLock.Unlock()

	connections := connMgr.connections
	if conn, ok := connections[connID]; ok {
		conn.Stop()
		delete(connections, connID)
		fmt.Println("清除连接成功 ID:  ", connID)
		return
	}

	fmt.Println("清除连接失败 ID:  ", connID)
}
